package com.apache.common.plugins;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.datasource.DynamicDataSourceHolder;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.ius.IusSqlTools;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description:   为各类提供编号
 * 设备：SB001-->SB171027-001
 * 物料：WL171027-001
 * 部件：BJ171027-001
 * 成品：CP171027-001
 */
public class NumberFactoryPluginImpl implements CustomMethodPlugin {

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     */
    public Object doInvoke(Map<String, Object> param) {
        return null;
    }

    public Object beforeInvoke(Map<String, Object> param) {
        String objName = String.valueOf(param.get("objName"));
        if (Validator.isNotNull(objName)) {
            return buildProNo(objName, param);
        }
        return null;
    }

    public Object afterInvoke(Map<String, Object> param) {
        return null;
    }

    private Map<String, Object> buildProNo(String objName, Map<String, Object> param) {
        //erpShebei:SB--shebeiNo;erpWuliao:WL--wuliaoNo;erpBjIns:BJ--bjInsNo;erpCpIns:CP--cpInsNo
        IDao iusDao = (IDao) SpringContextLoader.getBean("iusPubDao");
        String proNo = "";
        String colName = "";
        if ("erpShebei".equals(objName)) {
            proNo = "SB";
            colName = "shebeiNo";
        } else if ("erpWuliao".equals(objName)) {
            proNo = "WL";
            colName = "wuliaoNo";
        } else if ("erpBjIns".equals(objName)) {
            proNo = "BJ";
            colName = "bjInsNo";
        } else if ("erpCpIns".equals(objName)) {
            proNo = "CP";
            colName = "cpInsNo";
        } else {
        }

        proNo = proNo + DateUtils.getToday().replaceAll("-", "").substring(2);//SB171101

        List<DataMap<String>> list = searchTableByParams(iusDao, objName,
                upperCharToUnderLine(colName), null);
        if (list.size() > 0) {
            DataMap<String> map = list.get(0);
            String no = map.get(colName);
            if (Validator.isNotNull(no)) {
                String lastNo[] = no.split("-");
                if (lastNo.length > 1) {
                    no = String.format("%03d", Integer.valueOf(lastNo[1]) + 1);
                } else {
                    no = "001";
                }
            }
            proNo = proNo + "-" + no;
        } else {
            proNo = proNo + "-001";
        }

        param.put(objName + "." + colName, proNo);
        return param;
    }

    private List searchTableByParams(IDao iusDao, String objName, String colName,
            ParamsVo paramsVo) {
        if (null == paramsVo)
            paramsVo = new ParamsVo();
        paramsVo.setParams("sqlKeyId", "ByObjInfo");

        paramsVo.setParams("modelTypes", "s_" + objName);
        paramsVo.setParams("orderBy", objName + "." + colName + " desc");
        DynamicDataSourceHolder.putDataSource("aieerp");//指定数据源
        String execSql = IusSqlTools.getInstance().dymicNativeSql(paramsVo);
        MethodParam params = new MethodParam("ByObjInfo", "", "",
                "com.apache.ius.sql.DymicMapper");
        params.setParams("dyncSql", execSql);
        paramsVo = null;
        return iusDao.select(params);
    }

    private String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

    public static void main(String[] args) {

        String now = DateUtils.getToday().replaceAll("-", "");
        System.out.println(now.substring(2));

        String no = "ttt-001";
        String number = String.format("%03d", Integer.valueOf(no.split("-")[1]) + 1);
        System.out.println(number);

    }
}
